package com.nuo.backend.modules.security.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nuo.backend.common.exception.GlobalException;
import com.nuo.backend.common.utils.Constant;
import com.nuo.backend.modules.security.entity.SecRoleEntity;
import com.nuo.backend.modules.security.entity.SecUserRoleEntity;
import com.nuo.backend.modules.security.po.IdPO;
import com.nuo.backend.modules.security.po.UpdatePwdPO;
import com.nuo.backend.modules.security.service.SecRoleService;
import com.nuo.backend.modules.security.service.SecUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.nuo.backend.modules.security.entity.SecUserEntity;
import com.nuo.backend.modules.security.service.SecUserService;
import com.nuo.backend.common.utils.PageUtils;
import com.nuo.backend.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 系统用户
 *
 * @author nuo
 * @email 3033616351@qq.com
 * @date 2022-12-04 01:55:55
 */
@RestController
@RequestMapping("sec/user")
public class SecUserController {
    @Autowired
    private SecUserService secUserService;

    @Autowired
    private SecUserRoleService secUserRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        SecUserEntity secUser = (SecUserEntity) secUserService.getUserBySec().get("user");
        Set<Long> roleIdSet = secUser.getSecRoleList().stream().map(SecRoleEntity::getRoleId).collect(Collectors.toSet());
        // TODO root 获取全部角色的用户, 普通用户获取当前用户创建的用户
        if (!roleIdSet.contains(1L)) {
            params.put("createUserId", secUser.getUserId());
        }
        PageUtils page = secUserService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId){
		SecUserEntity secUser = secUserService.getById(userId);
        return R.ok().put("secUser", secUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody SecUserEntity secUser){
        secUser.setCreateUserId(secUserService.getUserId());
        // TODO 初始化密码
        secUser.setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PWD));
		secUserService.save(secUser);
        Set<SecUserRoleEntity> secUserRoleSet = secUser.getSecRoleList().stream().map(i -> new SecUserRoleEntity(null, secUser.getUserId(), i.getRoleId())).collect(Collectors.toSet());
        secUserRoleService.saveBatch(secUserRoleSet);
        // TODO 清除权限缓存
        secUserService.clearUserAuthorityBySecUserId(secUser.getUserId());
        return R.ok();
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd")
    public R resetPwd(@RequestBody IdPO po){
        // TODO 重置密码
        secUserService.updateById(new SecUserEntity().setUserId(po.getId()).setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PWD)));
        return R.ok();
    }

    /**
     * 重置密码
     */
    @RequestMapping("/updatePwd")
    public R updatePwd(@RequestBody UpdatePwdPO po){
        SecUserEntity secUser = (SecUserEntity) secUserService.getUserBySec().get("user");
        if (bCryptPasswordEncoder.matches(po.getOldPwd(), secUser.getPassword())) {
            secUserService.updateById(secUser.setPassword(bCryptPasswordEncoder.encode(po.getNewPwd())));
        } else {
            return R.error("原密码输入有误, 请重新输入...");
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody SecUserEntity secUser){
        secUserService.updateById(secUser);
        secUserRoleService.remove(new LambdaQueryWrapper<SecUserRoleEntity>().eq(SecUserRoleEntity::getUserId, secUser.getUserId()));
        Set<SecUserRoleEntity> userRoleSet = secUser.getSecRoleList().stream().map(i -> new SecUserRoleEntity(null, secUser.getUserId(), i.getRoleId())).collect(Collectors.toSet());
        secUserRoleService.saveBatch(userRoleSet);
        // TODO 清除权限缓存
        secUserService.clearUserAuthorityBySecUserId(secUser.getUserId());
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] userIds){
		secUserService.removeByIds(Arrays.asList(userIds));
        secUserRoleService.remove(new LambdaQueryWrapper<SecUserRoleEntity>().in(SecUserRoleEntity::getUserId, Arrays.asList(userIds)));
        // TODO 清除权限缓存
        Arrays.stream(userIds).forEach(i -> secUserService.clearUserAuthorityBySecUserId(i));
        return R.ok();
    }

}
